<template>
  <div id="equipmentPage">
    <h2 style="margin-bottom: 16px">
      {{ route.query?.id ? '修改设备' : '新增设备' }}
    </h2>

    <!-- 图片上传组件 -->
    <PictureUpload
      :picture-url="formState.imageUrl"
      :on-success="handleImageSuccess"
      :category="1"
      style="width: 200px; margin-bottom: 20px"
    />

    <a-form
      name="equipmentForm"
      layout="vertical"
      :model="formState"
      @finish="handleSubmit"
    >
      <!-- 器材名称 -->
      <a-form-item
        label="器材名称"
        name="equipmentName"
        :rules="[{ required: true, message: '请输入器材名称!' }]"
      >
        <a-input
          v-model:value="formState.equipmentName"
          placeholder="请输入器材名称"
          allow-clear
        />
      </a-form-item>

      <!-- 器材价格 -->
      <a-form-item
        label="价格（元）"
        name="equipmentPrice"
        :rules="[
          { required: true, message: '请输入价格!' },
          { type: 'number', min: 0, message: '价格不能小于0' }
        ]"
      >
        <a-input-number
          v-model:value="formState.equipmentPrice"
          :precision="2"
          style="width: 100%"
        />
      </a-form-item>

      <!-- 使用说明 -->
      <a-form-item
        label="使用说明"
        name="equipmentInstructions"
        :rules="[{ required: true, message: '请输入使用说明!' }]"
      >
        <a-textarea
          v-model:value="formState.equipmentInstructions"
          :rows="4"
          placeholder="请输入详细的使用说明..."
        />
      </a-form-item>

      <!-- 器材描述 -->
      <a-form-item label="器材描述" name="description">
        <a-textarea
          v-model:value="formState.description"
          :rows="3"
          placeholder="请输入器材描述..."
        />
      </a-form-item>
      <!-- 分类选择 -->
      <a-form-item label="设备分类" required>
        <div class="category-select">
          <a-select
            v-model:value="selectedCategory"
            placeholder="请选择一级分类"
            style="width: 200px; margin-right: 16px"
            @change="handleCategoryChange"
          >
            <a-select-option
              v-for="category in categoryList"
              :key="category.id"
              :value="category.id!"
            >
              {{ category.categoryName }}
            </a-select-option>
          </a-select>

          <a-select
            v-model:value="subSelectedCategory"
            placeholder="请选择二级分类"
            style="width: 200px"
            :disabled="!selectedCategory"
          >
            <a-select-option
              v-for="subCategory in subCategoryList"
              :key="subCategory.id"
              :value="subCategory.id!"
            >
              {{ subCategory.categoryName }}
            </a-select-option>
          </a-select>
        </div>
      </a-form-item>
      <!-- 标签选择 -->
      <a-form-item label="设备标签">
        <a-select
          v-model:value="selectedTagList"
          mode="multiple"
          style="width: 100%"
          placeholder="请选择标签"
        >
          <a-select-option
            v-for="tag in tagList"
            :key="tag.id"
            :value="tag.id!"
          >
            {{ tag.labelName }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item>
        <a-button
          type="primary"
          html-type="submit"
          style="width: 100%"
        >
          {{ route.query?.id ? '保存修改' : '创建器材' }}
        </a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, onMounted, ref, watch, nextTick } from 'vue'
import { message } from 'ant-design-vue'
import { useRoute, useRouter } from 'vue-router'
import PictureUpload from '@/components/PictureUpload.vue'
import {
  addUsingPost,
  getDetailUsingPost, updateUsingPost
} from '@/api/equipmentInfoController'
import EquipmentCategoryDTO = API.EquipmentCategoryDTO
import EquipmentLabelDTO = API.EquipmentLabelDTO
import {
  queryCategoryByPrimaryUsingPost,
  queryCategoryParentUsingPost,
  queryPrimaryCategoryUsingGet
} from '@/api/equipmentCategoryController.ts'
import { queryAllUsingGet } from '@/api/equipmentLabelController.ts'

interface FormState {
  equipmentName: string
  equipmentPrice: number | null
  description: string
  imageUrl: string
  equipmentInstructions: string
}

const router = useRouter()
const route = useRoute()

//一级分类，二级分类，标签
const categoryList = ref<EquipmentCategoryDTO[]>([])
const selectedCategory = ref<number>(0)
const subCategoryList = ref<EquipmentCategoryDTO[]>([])
const subSelectedCategory = ref<number>(0)
const tagList = ref<EquipmentLabelDTO[]>([])
const selectedTagList = ref<number[]>([])

//监听器，监视分类和标签发生的变化
watch([selectedCategory, subSelectedCategory], ([newCat, newSubCat]) => {
  formState.categoryId = newSubCat // 最终使用二级分类ID
})

watch(selectedTagList, (newVal) => {
  formState.labelIds = newVal
})

const formState = reactive<API.EquipmentInfoDTO>({
  equipmentName: '',
  equipmentPrice: null,
  description: '',
  imageUrl: '',
  equipmentInstructions: '',
  categoryId: null,
  labelIds: []
})

// 图片上传成功回调
const handleImageSuccess = (picture: API.PictureVO) => {
  formState.imageUrl = picture.url
}

// 提交处理
const handleSubmit = async () => {
  try {
    const payload = { ...formState }

    if (route.query?.id) {
      console.log("我正在进行修改")
      // 修改逻辑
      const res = await updateUsingPost({
        id: route.query.id,
        ...payload
      })
      if (res.data.code === 0) {
        message.success('修改成功')
        router.push('/equipment/equipmentManage')
      }
    } else {
      // 新增逻辑
      const res = await addUsingPost(payload)
      if (res.data.code === 0) {
        message.success('创建成功')
        router.push('/equipment/equipmentManage')
      }
    }
  } catch (e: any) {
    message.error(`操作失败: ${e.message}`)
  }
}

// 加载详情数据
// const loadDetailData = async () => {
//   const id = route.query?.id
//   if (!id) return
//
//   try {
//     const res = await getDetailUsingPost({ id: id as number })
//     if (res.data.code === 0 && res.data.data) {
//       Object.assign(formState, res.data.data)
//     }
//   } catch (e: any) {
//     message.error('数据加载失败')
//   }
// }
// 加载详情数据时处理分类回显
const loadDetailData = async () => {
  const id = route.query?.id
  if (!id) return

  try {
    const res = await getDetailUsingPost({ id: id as number })
    if (res.data.code === 0 && res.data.data) {
      const data = res.data.data

      // 处理分类回显
      if (data.categoryId) {
        // 需要接口支持根据二级分类ID查询父分类
        const parentRes = await queryCategoryParentUsingPost({
          id: data.id,
          categoryId: data.categoryId
        })
        if (parentRes.data.data) {
          // 设置一级分类并加载子分类
          selectedCategory.value = parentRes.data.data.id
          console.log('sssssssssssselectedCategory', selectedCategory.value)
          await handleCategoryChange() // 等待子分类加载
          // 等待DOM更新
          await nextTick()
          // 设置二级分类选中值
          subSelectedCategory.value = data.categoryId
        }
      }

      // 处理标签回显
      // if (data.labelIds) {
      //   selectedTagList.value = data.labelIds
      // }
      // 处理标签回显
      if (data.labelIds) {
        selectedTagList.value = data.labelIds.filter(id =>
          tagList.value.some(tag => tag.id === id)
        )
      }
      Object.assign(formState, data)
    }
  } catch (e) {
    message.error('数据加载失败')
  }
}

onMounted(() => {
  getTagCategoryOptions()
  loadDetailData()
})

//获取一级分类和标签
const getTagCategoryOptions = async () => {
  const res = await queryPrimaryCategoryUsingGet()
  const resd = await queryAllUsingGet()
  if (res.data.code === 0 && res.data.data && resd.data.code === 0 && resd.data.data) {
    categoryList.value = res.data.data ?? []
    tagList.value = resd.data.data ?? []
  }
}


// 获取二级分类时重置选择
const handleCategoryChange = async () => {
  subCategoryList.value = []
  subSelectedCategory.value = undefined
  if (selectedCategory.value) {
    const res = await queryCategoryByPrimaryUsingPost({
      parentId: selectedCategory.value
    })
    if (res.data.code === 0) {
      subCategoryList.value = res.data.data || []
    }
  }
}
</script>

<style scoped>
#equipmentPage {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}
</style>
